package com.tx.service;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description: http请求
 * @author: bluewelkin
 *  for i in range(600000,604000):
 *         cl = 'http://hq.sinajs.cn/list=sh'
 *         url = '%s%d' %(cl,i)
 *         #url='http://hq.sinajs.cn/list=sh601918'
 *         page = urllib.request.urlopen(url)
 *         print (page)
 *         stock_data = page.read().split('"')[1]
 * * @create: 2019-10-31 16:14
 * */
public class HttpClientMain {
    // 发送请求的url
    public static final String REQUEST_URL = "http://hq.sinajs.cn/list=sh6000000";
/*    int i;

    for(int i=60000;i <= 604000;i++){

    }*/

    /**
     * 测试发送GET请求
     */
    public void get() {
        // 1. 创建一个默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 2. 创建一个httpget对象
            HttpGet httpGet = new HttpGet(REQUEST_URL);
            System.out.println("executing GET request " + httpGet.getURI());
            // 3. 执行GET请求并获取响应对象
            CloseableHttpResponse resp = client.execute(httpGet);
            try {
                // 4. 获取响应体
                HttpEntity entity = resp.getEntity();
                System.out.println("------");
                // 5. 打印响应状态
                System.out.println(resp.getStatusLine());
                // 6. 打印响应长度和响应内容
                if (null != entity) {
                    System.out.println("Response content length = " + entity.getContentLength());
                    long a= entity.getContentLength();
                    InputStream b =entity.getContent();

                    System.out.println("Response content is:\n" + EntityUtils.toString(entity));
                }
                System.out.println("------");
            } finally {
                // 7. 无论请求成功与否都要关闭resp
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 8. 最终要关闭连接，释放资源
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
